<?php
/**
 * Created by PhpStorm.
 * User: mengkang <i@mengkang.net>
 * Date: 2017/10/24 下午11:59
 */

define("SERVER_IP", "0.0.0.0");
define("SERVER_PORT", 9512);

$server = new \swoole_server(SERVER_IP, SERVER_PORT);

$server->set(array(
    'worker_num'            => 1,
    'open_length_check'     => true,        // 开启协议解析
    'package_length_type'   => 'N',         // 长度字段的类型
    'package_length_offset' => 0,           // 第4个字节开始是包长度
    'package_body_offset'   => 4,           // 第8个字节开始计算长度
    'package_max_length'    => 2000000,     // 协议最大长度
));

$server->on('connect', function ($server, $fd) {
    echo "connection open: {$fd}\n";
});
$server->on('receive', function ($server, $fd, $reactor_id, $data) {
    $body = substr($data, 4);  // 获取数据

    var_dump($body);

    $response = json_encode(['uid' => 1000]);
    $len = strlen($response);

    $content = pack('N', $len) . $response;
    $server->send($fd, $content);
});

$server->on('close', function ($server, $fd) {
    echo "connection close: {$fd}\n";
});
$server->start();


